import Router from '../../utils/router';
import base from '../../config/base.js';
import service from '../../services/specialarea.js';
import Record_server from '../../services/record-stat';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon_friend_list: base.static + 'specialarea/sp-share-friendlist.png',
    icon_friend: base.static + 'specialarea/sp-share-friend.png',
    icon_mask_sellout: base.static + 'store/csellout.png',
    icon_overseas: base.static + 'detail/haigou.png',
    store_id: '',
    user_id: '',
    slgsid: '',
    goodsList: [],
    endBloon: true,
    loadBloon: true,
    page: 1,
    showModel: false,
    canvasWH: {
      w: 530,
      h: 810
    },
    shareJSON: {
      bgImg: {//背景图
        w: 530, h: 810, x: 0, y: 0,
      },
      ewmImg: {//二维码位置
        w: 140, h: 140, x: 352, y: 622
      },
      txImg: {//微信头像
        w: 140, h: 140, x: 36, y: 622
      },
      invite_name: {
        x: 426, y: 787, size: 24, txt: '长按扫码进入专场'
      },
      user_nickname: {
        x: 106, y: 787, size: 24,
      }
    },
    canvasPricePositionArr:[ 
      {
        x: 230, y: 596, size: 18, lx: 326, again: 'left', 
      },
      {
        x: 360, y: 276, size: 18, lx: 490, again: 'right',
      },
      {
        x: 244, y: 276, size: 18, lx: 330, again: 'right',
      },
      {
        x: 84, y: 276, size: 18, lx: 170, again: 'right',
      },
      {
        x: 84, y: 436, size: 18, lx: 170, again: 'right',
      },
      {
        x: 84, y: 596, size: 18, lx: 170, again: 'right',
      },
    ], //canvas价格位置
    cnavasPriceArr: '', //canvas商品价格
    canvas_bg: '', 
    avatar: '',
    tempFilePathAvatar: '', //头像备用图
    user_nickname: '',
    share_img_temp: false, //canvas图片地址
    special_name: '', //专题名称
    special_banner: '',
    hours: null, //倒计时小时
    minutes: '', //倒计时分钟
    seconds: '', //倒计时秒
    background_color: '',
    viewTimeNum: '', //浏览倒计时
    viewTimeTostBloon: true, //tost是否显示
    imgList: '',
    transmit: {
      style: 'position:absolute;width:100%;height:100%;right:0rpx;top:0rpx;opacity:0;',
      value: ''
    },
    signres: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let user_info = wx.getStorageSync('user_info') || {lastView:{seid: ''}}
    that.setData({
      slgsid: options.slgsid,
      store_id: user_info.lastView.seid,
      user_id: user_info.id,
      avatar: user_info.avatar,
      user_nickname: user_info.user_nickname
    })
    that.specialList(1, options.slgsid, options.entrance)
    if (options.entrance && options.entrance == "luckDraw"){
      //抽奖进入
      that.viewGooodsTimer(60);
    }
    //头像备用图
    wx.downloadFile({
      url: base.static + 'store/logo2.png',
      success: function (res) {
        if (res.statusCode === 200) {
          that.setData({
            tempFilePathAvatar: res.tempFilePath
          })
        }
      }
    })
  },
  // 抽奖浏览倒计时
  viewTimer: null,
  viewGooodsTimer: function (second) {
    let that = this;
    that.viewTimer = setTimeout(function () {
      if (second <= 0) {
        that.viewTimer = null
        that.addLuckNum();
      } else {
        second--
        that.setData({
          viewTimeNum: second
        })
        that.viewGooodsTimer(second);
      }
    }, 1000)
  },
  // 增加抽奖机会
  addLuckNum: function(){
    let that = this;
    let params = {
      name: 7
    }
    service.invitedsign(params, function (res) {
      if (res.code && res.code == 1) {
        that.data.signres = res.data.sign
        if (that.data.viewTimeTostBloon && res.data.sign ==1) {
          wx.showToast({
            title: '任务完成',
            icon: 'none'
          })
        } else if (res.data.sign == 0){
          wx.showToast({
            title: '一天只能领取一次哦~',
            icon: 'none'
          })
        }
      }
    });
  },
  //图片列表
  specialImgList: function (slgsid) {
    let that = this;
    let params = {
      offset: 50,
      page: 1
    }
    service.getspecialtype(params, function (res) {
      if (res.code && res.code == 1) {
        let imgarr = res.data.list
        for (let i = 0; i < imgarr.length; i++){
          if (imgarr[i].slgsid == slgsid){
            imgarr.splice(i, 1);
            break
          }
        }
        that.setData({
          imgList: imgarr,
        })
      }
      wx.stopPullDownRefresh()
    });
  },
  // 搜索其他列表
  goOtherList: function (e) {
    let that = this;
    that.setData({
      imgList: '',
      goodsList: [],
      endBloon: true,
      loadBloon: true,
      slgsid: e.currentTarget.dataset.slgsid
    })
    that.goodstimer = null
    that.specialList(1, e.currentTarget.dataset.slgsid)
  },
  //商品列表
  specialList: function (page, slgsid, entrance){
    let that = this;
    let params = {
      slgsid: slgsid,
      page: page,
      offset: 10
    }
    service.getspecialList(params, function (res) {
      if (res.code && res.code == 1) {
        let strarr = that.data.goodsList.concat(res.data.list);
        that.setData({
          goodsList: strarr,
          endBloon: true,
          page: page + 1,
        })
        if (strarr.length == res.data.count) {//是否到底
          that.setData({
            loadBloon: false,
          })
          //加载图片列表
          that.specialImgList(slgsid)
        }
        if (page ==1){//设置页面标题
          wx.setNavigationBarTitle({
            title: res.data.special_goods.special_name
          })
          that.setData({
            special_name: res.data.special_goods.special_name,
            canvas_bg: 'https:' + res.data.special_goods.share_url + '?x-oss-process=image/resize,l_700',
            special_banner: 'https:' + res.data.special_goods.special_banner,
            background_color: res.data.special_goods.bg_color
          })
          that.data.cnavasPriceArr = res.data.special_goods.prices
          that.getremainingtime(res.data.special_goods.end_time)
        }
        // 从卖家进入
        if (entrance && entrance == 'seller') {
          that.setData({
            showModel: true,
          })
          that.createNewImg()
        }
      } else if (res.code == 0) {//活动结束
        wx.showModal({
          title: '提示',
          content: '本专场活动已结束，下次早点来哦~',
          confirmText: '其他专场',
          success: function (resStr) {
            if (resStr.confirm) {
              Router.go('specialhome','')
            } else if (resStr.cancel) {
              Router.go('store', ``)
            }
          }
        })
      }
      wx.stopPullDownRefresh()
    });
  },
  // 倒计时
  goodstimer: null,
  getremainingtime(time) {
    let that = this;
    that.goodstimer = setTimeout(function () {
      if (time <= 0) {
        that.setData({
          hours: '00',
          minutes: '00',
          seconds: '00',
        });
        that.goodstimer = null
        wx.showModal({
          title: '提示',
          content: '本专场活动已结束',
          confirmText: '其他专场',
          success: function (resStr) {
            if (resStr.confirm) {
              Router.go('specialhome', '')
            } else if (resStr.cancel) {
              Router.go('store', ``)
            }
          }
        })
      } else {
        time = time - 1;
        that.setData({
          hours: parseInt(time / 60 / 60) >= 10 ? parseInt(time / 60 / 60) : '0' + parseInt(time / 60 / 60),
          minutes: parseInt(time / 60 % 60) >= 10 ? parseInt(time / 60 % 60) : '0' + parseInt(time / 60 % 60),
          seconds: parseInt(time % 60) >= 10 ? parseInt(time % 60) : '0' + parseInt(time % 60),
        });
      }
      if (that.goodstimer) {
        that.getremainingtime(time)
      }
    }, 1000)
  },
  // 点击分享
  shareSpecial: function(){
    let that = this;
    that.setData({
      showModel: true
    })
    if (!that.data.share_img_temp) { 
      that.createNewImg()
    }
  }, 
  // 隐藏分享
  hideShowModel: function () {
    wx.hideLoading()
    this.setData({
      showModel: false
    })
  },
  // 点击保存图片
  saveCanvasImg: function(){
    let that = this;
    if (that.data.share_img_temp){
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.writePhotosAlbum'] == false) {
            // 取消授权
            wx.showModal({
              title: '提示',
              content: '您未授权保存到相册功能，设置后正常使用',
              success: function (res) {
                wx.openSetting({
                  success(res) { }
                })
              }
            })
          } else {
            wx.saveImageToPhotosAlbum({
              filePath: that.data.share_img_temp,
              success() {
                wx.showToast({
                  title: '已保存至相册',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    }else{
      wx.showToast({
        title: '图片还没绘制完毕请稍等',
        icon: 'none'
      })
    }
  },
  createNewImg: function(){//开始画图
    let that = this;
    let shareJSON = that.data.shareJSON;
    var context = wx.createCanvasContext('myCanvas');
    wx.showLoading({
      title: '图片绘制中',
    });
    //清除  画布 内容
    context.clearRect(0, 0, that.data.canvasWH.w, that.data.canvasWH.h);
    that.setWxbg(context)
  },
  setWxbg: function(context) { //背景
    let that = this
    let bgImg = that.data.shareJSON.bgImg;
    try {
      wx.downloadFile({
        url: that.data.canvas_bg,
        success(res) {
          if (res.statusCode == 200) {
            context.drawImage(res.tempFilePath, bgImg.x, bgImg.y, bgImg.w, bgImg.h);
          }
          let cnavasPriceArr = that.data.cnavasPriceArr;
          let po = that.data.canvasPricePositionArr;
          cnavasPriceArr.forEach((item, index) => {
            try { //价格
              context.setFillStyle('#fff')
              context.setFontSize(po[index].size);
              context.fillText(item.discount + '折', po[index].x, po[index].y);
              //折扣
              context.setStrokeStyle('#FE3F3E')
              context.moveTo(po[index].lx, po[index].y)
              context.lineTo(po[index].lx, po[index].y)
              context.stroke()
              context.setFontSize(po[index].size);
              context.setTextAlign(po[index].again)
              context.fillText('￥' + item.sale_price, po[index].lx, po[index].y);
            }catch(e){}
          })
          that.setWxtx(context)
        }, fail(res) {
          wx.showToast({
            title: '背景下载失败',
            icon: 'none'
          })
        }
      })
    } catch (err) {
    }
  },
  setWxma: function(context) { //二维码
    let that = this;
    let store_id = that.data.store_id;
    let ewmImg = that.data.shareJSON.ewmImg;
    let user_id = wx.getStorageSync('user_info').id
    try {
      let user_info = that.data.user_info,
        auth_token = wx.getStorageSync('auth_token'),
        path = encodeURIComponent('pages/specialarea/specialtype?slgsid=' + that.data.slgsid + '&store_id=' + store_id + '&sharerecord=specialtypecode' + '&user_id=' + user_id),
        url = base.apiUrl + '/getCustomerQrCode?' + '&path=' + path + '&scene=1012' + '&auth_token=' + auth_token;
      wx.downloadFile({
        url: url,
        success(res) {
          if (res.statusCode == 200) {
            that.circleImg(context, res.tempFilePath, ewmImg.x, ewmImg.y, ewmImg.w, ewmImg.h, ewmImg.w)
            that.setWxtextfn(context, that.data.shareJSON.invite_name);
          }
          else if (res.statusCode == 401) {
            wx.showToast({
              title: '登录过期',
              icon: 'none'
            })
            setTimeout(() => {
              const currentPages = getCurrentPages();
              const fromPageUrl = '/' + currentPages[currentPages.length - 1].__route__ || '';
              Router.go('register', `to=${encodeURIComponent(fromPageUrl)}`);
            }, 500)
          }
        }, fail(res) {
          wx.showToast({
            title: '小程序码绘制失败',
            icon: 'none'
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: '小程序码绘制失败',
        icon: 'none'
      })
    }
  },
  setWxtx: function(context) {//头像
    let that = this
    let txImg = that.data.shareJSON.txImg;
    if (that.data.user_nickname.length > 5) {
      that.data.shareJSON.user_nickname.txt = that.data.user_nickname.substr(0, 5) + '...推荐';
    }else{
      that.data.shareJSON.user_nickname.txt = that.data.user_nickname + '推荐'
    }
    try {
      wx.downloadFile({
        url: that.data.avatar,
        success(res) {
          if (res.statusCode == 200) {
            that.circleImg(context, res.tempFilePath, txImg.x, txImg.y, txImg.w, txImg.h, txImg.w)
            that.setWxtextfn(context, that.data.shareJSON.user_nickname);
          }
        }, fail(res) {
          context.drawImage(that.data.tempFilePathAvatar, txImg.x, txImg.y, txImg.w, txImg.h);
          that.setWxtextfn(context, that.data.shareJSON.user_nickname);
        }
      })
    } catch (err) {

    }
  },
  circleImg: function(context, img, x, y, r) { //切圆方法
    let that = this;
    try {
      context.save();
      context.beginPath();
      r = r / 2;
      var d = 2 * r;
      var cx = x + r;
      var cy = y + r;
      context.arc(cx, cy, r, 0, 2 * Math.PI);
      context.clip();
      context.drawImage(img, x, y, d, d);
      context.restore();
    } catch (err) {
      wx.showToast({
        title: '头像切圆失败',
        icon: 'none'
      })
    }
  },
  setWxtextfn: function(context, obj){
    let that = this;
    context.setFillStyle('#fff')
    try {
      if (obj.txt != "长按扫码进入专场"){
        context.setStrokeStyle('#FE6462')
        context.moveTo(106, 777)
        context.lineTo(106, 788)
        context.stroke()
        context.setFontSize(obj.size);
        context.setTextAlign('center')
        context.fillText(obj.txt, obj.x, obj.y);
        that.setWxma(context)
      }else{
        context.setFontSize(obj.size);
        context.fillText(obj.txt, obj.x, obj.y);
        that.last(context)
      }
    } catch (err) {
      wx.showToast({
        title: '绘制文字失败',
        icon: 'none'
      })
    }
  },
  last: function(context) { //绘制完成
    let that = this;
    try {
      context.draw(false, function (e) {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: function (res) {
            wx.hideLoading()
            that.setData({
              share_img_temp: res.tempFilePath
            });
            wx.hideLoading()
          }, fail(res) {
            wx.hideLoading()
            wx.showToast({
              title: '绘制失败',
              icon: 'none'
            })
          }
        })
      })
    } catch (err) {
      wx.showToast({
        title: '绘制失败',
        icon: 'none'
      })
    }
  },
  // 回首页
  goStore: function(){
    Router.go('store',``)
  },
  //去商品详情
  goDetails: function (e) {
    let that = this;
    let goods_id = e.currentTarget.dataset.goodsid;
    let store_id = that.data.store_id;
    Router.go('detail', `store_id=${store_id}&goods_id=${goods_id}`);
    that.viewRecord(goods_id, "click");
  },
  queryMultipleNodes(scroll) {
    let that = this;
    if (that.data.goodsList == "") {
      return
    }
    let query = wx.createSelectorQuery();
    let s = wx.getSystemInfoSync().windowHeight;
    query.selectAll('.test').boundingClientRect(function (rects) {
      let len = rects.length
      for (let i = 0; i<len; i++) {
        let rect = rects[i];
        try {
          if (rect && rect.top && 0 < rect.top && rect.bottom < s) {
            that.viewRecord(rect.id, "view")
          }
        } catch (e) { }
      }
    }).exec()
  },
  //滚动和点击屏幕记录
  viewRecord: function (goodsid, act) {
    let that = this;
    let params = {
      name: "ltxx_buyer",
      page: 'special_type',
      position: '',
      productid: goodsid,
      userid: that.data.user_id,
      storeid: that.data.store_id,
      act: act,
      env: app.globalData.env
    }
    Record_server.recordstat(params, function () { });
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.queryMultipleNodes(e.scrollTop)
    }, 500);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    if (!that.data.viewTimeTostBloon && that.data.viewTimeNum == 0 && that.data.signres == 1) {
      //浏览60秒
      wx.showToast({
        title: '任务完成',
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.data.viewTimeTostBloon = false
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    if (that.goodstimer) { //清除定时器
      clearTimeout(that.goodstimer)
    }
    if (that.viewTimer) {
      clearTimeout(that.viewTimer)
    };
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.goodstimer) { //清除定时器
      clearTimeout(this.goodstimer)
    }
    this.setData({
      goodsList: [],
      endBloon: true,
      loadBloon: true,
      imgList: '',
    })
    this.specialList(1, this.data.slgsid,'')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this
    if (that.data.loadBloon && that.data.endBloon){
      that.setData({
        endBloon: false,
      })
      that.specialList(that.data.page, that.data.slgsid,'')
    }
  },
  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (res) {
    wx.hideLoading()
    let that = this;
    let paths = 'pages/specialarea/specialtype?slgsid=' + that.data.slgsid + '&store_id=' + that.data.store_id + '&sharerecord=specialtypecard' + '&store_id=' + that.data.store_id + '&user_id=' + that.data.user_id;
    that.setData({
      showModel: false
    })
    return {
      title: that.data.special_name,
      path: paths
      // imageUrl: store_share_img
    }
  }
})